package thread;


import java.util.PriorityQueue;

class MyTimertask implements Comparable<MyTimertask>{
    private long time;
    private Runnable runnable;
    public MyTimertask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimertask o) {
        return (int) (this.time-o.time);
    }
}



class MyTimer {
    private Thread t;
    private PriorityQueue<MyTimertask> queue = new PriorityQueue();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimertask task = new MyTimertask(runnable, delay);
            queue.offer(task);
            locker.notify();
        }
    }

    public MyTimer() {
        t = new Thread(() -> {
            try {
                synchronized (locker) {
                    while (true) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimertask curtask = queue.peek();
                        if (System.currentTimeMillis() >= curtask.getTime()) {
                            queue.poll();
                            curtask.run();
                        } else {
                            locker.wait(curtask.getTime() - System.currentTimeMillis());
                        }
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();

    }
}

public class ThreadDemo8 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
    }
}
